<template>
  <div
    class="normal-home-hot-area-item preview"
    ref="hotRef"
    :style="wrapperStyle"
    @mousedown="handleMouseDown"
    @mouseover="handleMouseOver"
    @click="handleHotClick"
  >
    <span class="range"
      ><span>热区{{ range + 1 }}</span></span
    >
  </div>
</template>
<script>
export default {
  props: {
    cdata: {
      type: Object,
      default() {
        return {};
      },
    },
    range: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      disX: 0,
      disY: 0,
    };
  },
  computed: {
    wrapperStyle() {
      const { width, height, top, left } = this.cdata;
      // return {
      //   width: width / this.ratio + "rem",
      //   height: height / this.ratio + "rem",
      //   top: top / this.ratio + "rem",
      //   left: left / this.ratio + "rem",
      // };
      return {
        width: width + "px",
        height: height + "px",
        top: top + "px",
        left: left + "px",
      };
    },
  },
  methods: {
    handleMouseOver(event) {
      event.stopPropagation();
      // 设置active 当前热区为选中热区
      // console.log(event);
    },
    handleMouseDown(event) {
      event.stopPropagation();
      this.disX = event.clientX - this.$refs.hotRef.offsetLeft;
      this.disY = event.clientY - this.$refs.hotRef.offsetTop;
      this.$nextTick(() => {
        document.onmousemove = this.handleMouseMove;
        document.onmouseup = this.handleMouseUp;
      });
    },
    handleMouseMove(event) {
      event.stopPropagation();
      let iL = event.clientX - this.disX;
      let iT = event.clientY - this.disY;
      const target = this.$refs.hotRef;
      const maxL = target.parentElement.offsetWidth - target.offsetWidth - 2;
      const maxT = target.parentElement.offsetHeight - target.offsetHeight - 2;
      // 最外层边界判断
      iL = Math.max(iL, 0);
      iT = Math.max(iT, 0);
      iL = Math.min(iL, maxL);
      iT = Math.min(iT, maxT);
      target.style.left = iL + "px";
      target.style.top = iT + "px";
    },
    handleMouseUp(event) {
      // if (!this.preview) return;
      event && event.stopPropagation();
      // this.$emit("change", this.range, this.$refs.hotRef);
      document.onmousemove = null;
      document.onmouseup = null;
      document.onmousecancel = null;
    },
    handleHotClick() {
      // console.log("非预览情况下点击跳转到对应链接地址");
    },
  },
};
</script>
<style lang="less" scoped>
.normal-home-hot-area-item {
  position: absolute;
  // border: 4px solid rgb(37, 49, 62);
  background: none;
  overflow: visible;
  &.preview {
    cursor: move;
    border: 1px solid #29b6b0;
    background: rgba(41, 182, 176, 0.25);
  }

  .range {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    pointer-events: none;
    color: #000;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 100%;
  }
}
</style>
